package com.lg.cms.controller.news;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lg.cms.dto.TemplateDTO;
import com.lg.cms.entity.*;
import com.lg.cms.service.*;
import com.lg.cms.utils.IpUtil;
import com.lg.cms.utils.RedisUtil;
import com.lg.cms.utils.StatsUtil;
import com.lg.cms.utils.SubjectUtil;
import com.lg.cms.vo.news.*;
import com.sun.xml.internal.messaging.saaj.packaging.mime.util.QEncoderStream;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 动态前台展示控制器
 * @Author: wuyuhang
 * @create: 2020-10-06 13:11
 * 功能列表:
 * 首页
 * 首页展示Model:
 * basePath(文章访问路径, 使用${basePath}css/a.css)   √
 * 轮播图(固定再某块可改变的轮播图)   √
 * 文章轮播图(第一页)              √
 * 文章视频(第一页)               √
 * 推荐(第一页)
 * 热点(热度最高的几条)
 * 栏目列表                    √
 * 文章轮播图page对象                  √
 * 文章视频page对象                   √
 * 推荐page对象
 * 列表页
 * 列表页展示Model:
 * 文章列表(第一页)
 * 某栏目文章page对象
 * 搜索页
 * 搜索到的文章page对象
 * 默认展示布局可为空Model:
 * 轮播图页
 * 详情页展示Model:
 * 某详细文章对象(文章类型为"轮播图"区别首页轮播图)
 * 文章页
 * 详情页展示Model:
 * 某详细文章对象(文章类型为"文章"区别首页轮播图)
 */
@Controller
@Slf4j
public class NewsController {

    @Autowired
    private TemplateService templateService;
    @Autowired
    private TemplateTypeService templateTypeService;
    @Autowired
    private TemplateTypePathService templateTypePathService;
    @Autowired
    private ArticleService articleService;
    @Autowired
    private ArticleTypeService articleTypeService;
    @Autowired
    private RotationService rotationService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private TagsService tagsService;
    @Autowired
    private CommentService commentService;
    @Resource
    private StatsUtil statsUtil;
    @Resource
    private RedisUtil redisUtil;

    /**
     * 首页展示
     * 轮播图(固定展示轮播图)(rotationList)
     * 推荐()
     * 热点()
     * 视频()
     * 图片()
     *
     * @param model
     * @return
     */
    @GetMapping("/shouye")
    public String index(Model model, HttpServletRequest request) {
        redisUtil.set("cms:pageSize", 2);
        TemplateDTO dto = templateService.getCurrentTemplate();
        model.addAttribute("rotationList", rotationService.getList()); //轮播图列表对象
        model.addAttribute("videoList", articleService.getListByVideo(null)); //视频列表对象(第一页)
        model.addAttribute("imageList", articleService.getListByImage(null)); //图片列表对象(第一页)
        model.addAttribute("recommendedArticleList", articleService.getListByRecommended()); //图片列表对象(第一页)
        model.addAttribute("recommendedCount", articleService.getPageByRecommended(1).getTotal()); //返回推荐文章的总数
        model.addAttribute("imageCount", articleService.getPageByImage(1, null).getTotal()); //图片总数
        model.addAttribute("videoCount", articleService.getPageByVideo(1, null).getTotal()); //视频总数
        this.setModel(model);
        model.addAttribute("request", request);
        model.addAttribute("basePath", dto.getBasePath());
        return dto.getIndexPath();
    }


    /**
     * 列表页展示
     *
     * @param model
     * @return
     */
    @GetMapping("/list/{id}")
    public String list(@PathVariable("id") Integer categoryId, Model model) {
        TemplateDTO dto = templateService.getCurrentTemplate();
        Category category = categoryService.getById(categoryId);
        CategoryVO categoryVO = new CategoryVO();
        if (category != null) {
//            如果栏目id不存在
//            return "redirect:/error/404";
            categoryVO = categoryService.toCategoryVO(category, null);
        }
        model.addAttribute("basePath", dto.getBasePath());
        model.addAttribute("currentCategoryVO", categoryVO);
        this.setModel(model);
        model.addAttribute("articleList", articleService.getListByCategoryId(categoryId));
        model.addAttribute("articleCount", articleService.getPageByCategoryId(categoryId, 1).getTotal());
        return dto.getListPath();
    }

    /**
     * 列表展示页(根据标签)
     *
     * @param tagsId
     * @param model
     * @return
     */
    @GetMapping("/tags_list/{id}")
    public String tagsList(@PathVariable("id") Integer tagsId, Model model) {
        System.out.println("进入tags_list");
        Tags tags = tagsService.getById(tagsId);
        TemplateDTO dto = templateService.getCurrentTemplate();
        model.addAttribute("articleList", articleService.getListByTagsId(tagsId));
        model.addAttribute("basePath", dto.getBasePath());
        model.addAttribute("currentTags", tagsService.toTagsVO(tags));
        model.addAttribute("articleCount", articleService.getPageByTagsId(tagsId, 1).getTotal());
        this.setModel(model);
        return dto.getTagsListPath();
    }

    /**
     * 图片列表页
     *
     * @param model
     * @return
     */
    @GetMapping("/image_list")
    public String imageList(Model model, String name) {
        TemplateDTO dto = templateService.getCurrentTemplate();
        Category category = categoryService.getOne(new QueryWrapper<Category>().eq("name", "图片"));
        QueryWrapper wrapper = new QueryWrapper();
        if (name != null)
            wrapper.like("title", name);
        model.addAttribute("imageList", articleService.getListByImage(wrapper));
        model.addAttribute("currentCategoryVO", categoryService.toCategoryVO(category, null));
        model.addAttribute("imageCount", articleService.getPageByImage(1, wrapper).getTotal());
        this.setModel(model);
        model.addAttribute("currentName", name);
        model.addAttribute("basePath", dto.getBasePath());
        return dto.getImageListPath();
    }

    /**
     * 视频列表页, 提供标题搜索
     *
     * @param model
     * @return
     */
    @GetMapping("/video_list")
    public String videoList(Model model, String name) {
        TemplateDTO dto = templateService.getCurrentTemplate();
        Category category = categoryService.getOne(new QueryWrapper<Category>().eq("name", "视频"));
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        if (name != null)
            wrapper.like("title", name);
        model.addAttribute("videoList", articleService.getListByVideo(wrapper));
        model.addAttribute("currentCategoryVO", categoryService.toCategoryVO(category, null));
        model.addAttribute("videoCount", articleService.getPageByImage(1, wrapper).getTotal());
        this.setModel(model);
        model.addAttribute("currentName", name);
        model.addAttribute("basePath", dto.getBasePath());
        return dto.getVideoListPath();
    }

    /**
     * 搜索页展示
     *
     * @param model
     * @return
     */
    @GetMapping("/select")
    public String select(Model model, String value, Boolean title, Integer pageNum) {
        Long start = System.currentTimeMillis();
        if (pageNum == null) {
            pageNum = 1;
        }
        QueryWrapper<Article> wrapper = new QueryWrapper();
        if (title == null) {
            title = false;
        }
        if (title) {
            wrapper.like("title", value);
            wrapper.isNotNull("title");
        } else {
            wrapper.like("content", value);
            wrapper.isNotNull("markdown_content");
        }
        Page<ArticleVO> page = articleService.getPageByWrapper(wrapper, pageNum, value);
        TemplateDTO dto = templateService.getCurrentTemplate();
        model.addAttribute("articleList", articleService.getListByWrapper(wrapper, value));
        model.addAttribute("page", page);
        model.addAttribute("pages", page.getPages());
        model.addAttribute("basePath", dto.getBasePath());
        model.addAttribute("currentValue", value);
        model.addAttribute("currentTitle", title);
        this.setModel(model);
        model.addAttribute("time", ((System.currentTimeMillis() - start) / 1000.0));
        return dto.getSelectPath();
    }

    /**
     * 文章页展示
     *
     * @param model
     * @param articleId
     * @return
     */
    @GetMapping("/info_article/{id}")
    public String infoArticle(@PathVariable("id") Integer articleId, Model model, HttpServletRequest request) {
//        System.out.println("进入文章详情");
        Article article = articleService.getById(articleId);
        if (article == null) {
//            System.out.println("404");
            return "redirect:/error/404";
        }
        ArticleVO articleVO = articleService.toArticleVO(article);
        if (articleVO.getCategoryName().equals("图片") || articleVO.getCategoryName().equals("视频")) {
//            System.out.println("404");
            return "redirect:/error/404";
        }
        TemplateDTO dto = templateService.getCurrentTemplate();
        model.addAttribute("currentCategoryVO", categoryService.toCategoryVO(categoryService.getById(articleVO.getArticle().getCategoryId()), null));
        model.addAttribute("article", articleVO);
        this.setModel(model);
        model.addAttribute("basePath", dto.getBasePath());
        model.addAttribute("commentList", commentService.getListByArticleId(articleId));
        model.addAttribute("commentCount", commentService.getPageByArticleId(articleId, 1).getTotal());
//        System.out.println(dto.getInfoArticlePath());
        statsUtil.addArticleView(articleId, IpUtil.getIpAddr(request));
        return dto.getInfoArticlePath();
    }


    /**
     * 文章图片页展示
     *
     * @param model
     * @return
     */
    @GetMapping("/info_image/{id}")
    public String infoRotation(@PathVariable("id") Integer articleId, Model model, HttpServletRequest request) {
        Article article = articleService.getById(articleId);
        if (article == null) {
            return "redirect:/error/404";
        }
        if (!categoryService.getById(article.getCategoryId()).getName().equals("图片")) {
            return "redirect:/error/404";
        }
        ImageVO imageVO = articleService.toImageVO(article);
        TemplateDTO dto = templateService.getCurrentTemplate();
        model.addAttribute("currentCategoryVO", categoryService.toCategoryVO(categoryService.getById(imageVO.getArticle().getCategoryId()), null));
        model.addAttribute("image", imageVO);
        this.setModel(model);
        model.addAttribute("basePath", dto.getBasePath());
        model.addAttribute("commentList", commentService.getListByArticleId(articleId));
        model.addAttribute("commentCount", commentService.getPageByArticleId(articleId, 1).getTotal());
        statsUtil.addArticleView(articleId, IpUtil.getIpAddr(request));
        return dto.getInfoImagePath();
    }

    /**
     * 文章视频页展示
     *
     * @param model
     * @return
     */
    @GetMapping("/info_video/{id}")
    public String infoVideo(@PathVariable("id") Integer articleId, Model model, HttpServletRequest request) {
        Article article = articleService.getById(articleId);
        if (article == null) {
//            System.out.println("404");
            return "redirect:/error/404";
        }
        if (!categoryService.getById(article.getCategoryId()).getName().equals("视频")) {
            return "redirect:/error/404";
        }
        VideoVO videoVO = articleService.toVideoVO(article);
        TemplateDTO dto = templateService.getCurrentTemplate();
        model.addAttribute("currentCategoryVO", categoryService.toCategoryVO(categoryService.getById(videoVO.getArticle().getCategoryId()), null));
        model.addAttribute("video", videoVO);
        this.setModel(model);
        model.addAttribute("basePath", dto.getBasePath());
        model.addAttribute("commentList", commentService.getListByArticleId(articleId));
        model.addAttribute("commentCount", commentService.getPageByArticleId(articleId, 1).getTotal());
        statsUtil.addArticleView(articleId, IpUtil.getIpAddr(request));
        return dto.getInfoVideoPath();
    }
    //无

    private void setModel(Model model) {
        User user = null;
        try{
            user = SubjectUtil.getUser();
        }catch (Exception e){}
        model.addAttribute("user", user);
        model.addAttribute("categoryList", categoryService.getList());
        model.addAttribute("pageSize", redisUtil.get("cms:pageSize"));
        model.addAttribute("hotspotList", articleService.getListByHotspot(100)); //热点排行
        model.addAttribute("tagsList", tagsService.getList()); //标签列表
    }
}